---
--类名: RankingView.lua
--创建日期: 2018-4-20
--创建人: 宋建邦
--功能描述: 排行榜视图
--

local UserBaseInfo = require("app.public.dao.UserBaseInfo")

local MoLayer = require("app.widget.MoLayer")
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local AvatarFactotry = require("app.public.avatar.AvatarFactory")
local HeadRender = require("app.widget.renders.HeadRender")
local TeamModel = app:getInst("TeamModel")
local socket = require "socket"
local PvpChallengeRankAwardView = require("app.pvp.views.PvpChallengeRankAwardView")
local TabsBtn = require("app.widget.TabsBtn")

local RankingView = class("RankingView",function()
    return MoLayer.new(true)
end)

local Res = {
    RankingScene = "ui2/ranking/Scene_ranking.csb",
    Lv1Node = "ui2/ranking/Node_rank_list_1.csb",
    Lv2Node = "ui2/ranking/Node_rank_list_2.csb",
    Lv3Node = "ui2/ranking/Node_rank_list_3.csb",
    PlayerNode = "ui2/ranking/Node_player.csb",
    PlayerNode1 = "ui2/ranking/Node_player_1.csb",
    TeamNode = "ui2/ranking/Node_player_team.csb",
    MemberNode = "ui2/ranking/Node_team_more.csb",
    MemberGroupNode = "ui2/ranking/Node_legion_more.csb",
    classIconPath = "art/class_icon/",
    cosplayIconPath = "art/rolePlay_icon/%s.png",
}

local function tostring3 (n)
    if n < 0 then
        return "-" .. tostring3(-n)
    end

    local rets = {}
    repeat
        if n >= 1000 then
            table.insert(rets, 1, string.format("%03d", math.fmod(n, 1000)) )
        else
            table.insert(rets, 1, tostring(math.fmod(n, 1000)))
        end
        n = math.floor(n/1000)
    until n <= 0
    return table.concat(rets, ",")
end

function RankingView:ctor(aRankingId, labelType)
    self.vsEvent = 1
    self.vsFoot = 2

    self:setNodeEventEnabled(true)

    self.mUINode = cc.uiloader:load(Res.RankingScene)
    self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width,display.height))
    ccui.Helper:doLayout(self.mUINode)

    self:addCloseListener()

    self.NodePool = custom.NodePool:getInstance()
    self.copyList = TeamModel:getCurSpeedDungeonIDs()

    self.rankMap = {}
    self.typeMap = {}

    self:initTypeTree()
    
    EM:on(RankingManager.RankChangeEventName, function(evt, rId)
        if RankingManager.serverrank[rId] then
            self:beginRefreshView(rId)
        end        
    end)

    self.rankList = self.mUINode:findChild("Panel/Panel_r/ListView1")
    self.lblMyScore = self.mUINode:findChild("Panel/Panel_r/text")
    self.lblMyScoreBg = self.mUINode:findChild("Panel/Panel_r/bg1")
    self.lblCurRank = self.mUINode:findChild("Panel/Panel_r/Panel_top/combat")
    self.lblCurTime = self.mUINode:findChild("Panel/Panel_r/Panel_top/time")
    self.columnPanel = self.mUINode:findChild("Panel/Panel_r/Panel_top")
    self.columnPanel_1 = self.mUINode:findChild("Panel/Panel_r/Panel_top_1")
    self.columnPanel_team = self.mUINode:findChild("Panel/Panel_r/Panel_top_team")
    self.btnGift = self.mUINode:findChild("Panel/Panel_r/btn_gift")
    self.columnPanel_team:hide()
    self.columnPanel_1:getChildByName("btn_tips"):addClickEventListener(function(sender)
        self:_showTips(sender) -- 目前只有显示赛季积分tips
    end)
    self._tipsPosX = self.columnPanel_1:getChildByName("btn_tips"):getPositionX()

    self.btnGift:addClickEventListener(function(sender)
        if not self.rankingRewardView then
            self.rankingRewardView = PvpChallengeRankAwardView.new()
            self:addChild(self.rankingRewardView)
        end
        self.rankingRewardView:show()
        self.rankingRewardView:updateViewByRankId(self.currentRank)
    end)

    self.noRankTip = self.mUINode:findChild("Panel/Panel_tips")

    local btns = {}
    for i = 1,2 do
        btns[i] = self.mUINode:findChild("Panel/Panel_tab/selected_btn_"..i)
    end

    local function onTabsBtn(index, btn)
        --self:_refreshViewByIndex(index)
        if index == 2 then
            --此处关掉这个界面打开角色的排行榜界面
            UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK,mode = "close", rankingId = aRankingId})
            UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK,mode = "open", rankingId = Enums.GuildRankType.GuildLv})
        end
    end

    self._tabsBtn = TabsBtn.new(btns, onTabsBtn, 1)


    self:initPage()

    self.btnGotoSelf = self.mUINode:findChild("Panel/Panel_r/Button")
    self.btnGotoSelf:addClickEventListener(function(sender)
        self:gotoSelf()
    end)

    -- self:requestRank(math.max(checknumber(aRankingId), 1))
    self:open(math.max(checknumber(aRankingId), 1))
    
    self.heads = {}
    self:schedule(self.update, 0)
end

function RankingView:onExit()
    EM:removeByName(RankingManager.RankChangeEventName)

    local function release(n)
        if n then
            n:release()
        end
    end

    release(self.lv1Node)
    release(self.lv2Node)
    release(self.lv3Node)
    release(self.playerNode)
    release(self.playerNode1)
    release(self.teamNode)
    release(self.memberNode)
    release(self.memberGroupNode)
end

local refreshItemStep = 5
function RankingView:update()
    if self.asyncRefreshViewId then
        self.noRankTip:setVisible(self.asyncRefreshCountMax <= 0)
        if RankingManager:isTeamRank(self.asyncRefreshViewId) then
            self:refreshTeamView(self.asyncRefreshViewId, refreshItemStep)
        else
            self:refreshView(self.asyncRefreshViewId, refreshItemStep)
        end
        self.asyncRefreshCount = self.asyncRefreshCount + refreshItemStep
        if self.asyncRefreshCount >= self.asyncRefreshCountMax then
            if self.lblMyScore then
                local rd = RankingManager.serverrank[self.asyncRefreshViewId]
                local rtxt = L("lua_code_text_306")
                if self.myPerRank > 0 then
                    rtxt = string.format(L("lua_code_text_173"), tostring(self.myPerRank))
                end
                local strMv = ""
                local ms = 0
                if RankingManager:isTeamRank(self.asyncRefreshViewId) then
                    ms = rd.mySec
                else
                    ms = rd.myScore
                end
                if self.columnsFmt == 1 then
                    strMv = tostring3(checknumber(ms))
                elseif self.columnsFmt == 2 then
                    strMv = string.format("%.2f", math.max(ms, 36)/3600)
                elseif self.columnsFmt == 3 then
                    local m = ms/60
                    local s = math.fmod(ms, 60)
            
                    strMv = string.format("%d:%02d", m, s)
                else
                    strMv = tostring(checknumber(ms))
                end
                if checknumber(ms) == 0 then
                    strMv = " "
                    rtxt = L("ranktips1")
                end
                self:setMyScore( string.format(L("lua_code_text_194"), strMv, rtxt))
            end

            self:refreshPage(self.asyncRefreshCountMax)
            
            self.asyncRefreshViewId = nil
            self.asyncRefreshCount = nil
            self.asyncRefreshCountMax = nil
        end
    end
    if #self.heads > 0 then
        local beg = socket.gettime()
        local endT = 0
        repeat
            local r = table.remove(self.heads, 1)
            AvatarFactotry.getOrCreateHeroIconPath(r.d,function(iconPath)
                if iconPath and not cc.isDead(r.c) then
                    r.c:show()
                    r.c:loadTexture(iconPath)
                end
            end)
            endT = socket.gettime()
        until(endT > beg + 0.03 or #self.heads <= 0)
    end
end

function RankingView:initPage()
    self.prePageBtn = self.mUINode:findChild("Panel/Panel_r/Panel_page/Button_1")
    self.nxtPageBtn = self.mUINode:findChild("Panel/Panel_r/Panel_page/Button_2")
    self.pageLbl = self.mUINode:findChild("Panel/Panel_r/Panel_page/num")

    self.prePageBtn:addClickEventListener(function(sender)
        self:gotoPage(-1)
    end)
    self.nxtPageBtn:addClickEventListener(function(sender)
        self:gotoPage(1)
    end)

    self.onScrollEvt = function(sender, evenType)        
        local cy = self.rankList:getContentSize().height - self.rankList:getInnerContainer():getPositionY()

        if self.pageStarts then
            local cp = self.pageCount
            for i, v in ipairs(self.pageStarts) do
                if cy > v:getPositionY() + 94 then
                    cp = math.max(i - 1, 1)
                    break
                end
            end

            if self.currentPage ~= cp then
                self.currentPage = cp
                self:refreshPageStatus()
            end            
        end        
    end
    self.rankList:addScrollViewEventListener(self.onScrollEvt)
end

function RankingView:refreshPage(cnt)
    self.pageCount = math.ceil(cnt/20)
    self.currentPage = math.min(1, self.pageCount)

    self:refreshPageStatus()
end

function RankingView:refreshPageStatus()
    self.pageLbl:setString(tostring(self.currentPage).."/"..tostring(self.pageCount))
end

function RankingView:gotoPage(off)
    local n = self.currentPage + off
    if n >= 1 and n <= #self.pageStarts then
        self.currentPage = n 
        self:gotoItem(self.pageStarts[n])
        self.pageLbl:setString(tostring(self.currentPage).."/"..tostring(self.pageCount))
    end
end

function RankingView:addCloseListener()
    local btnClose = self.mUINode:findChild("Panel/Button_back")
    btnClose:addClickEventListener(function(sender)
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK,mode = "close"})
    end)
end

function RankingView:open(aRid)
    local r = RankingManager.hcfg[checknumber(aRid)]
    local clv2 = RankingManager.ht[checknumber(r.belong)]
    local clv1 = RankingManager.ht[checknumber(clv2.belong)]

    if clv1 and self.typeMap[checknumber(clv1.ID)] then
        
        if not self.typeMap[checknumber(clv1.ID)].c.content.selected then
            self.typeMap[checknumber(clv1.ID)].c.select()
        end
        if clv2 and self.typeMap[checknumber(clv2.ID)] then
            
            if not self.typeMap[checknumber(clv2.ID)].c.content.selected then
                self.typeMap[checknumber(clv2.ID)].c.select()
            end
        end
        if r and self.rankMap[checknumber(r.ID)] then
            self.rankMap[checknumber(r.ID)].c.select()
        end
    end
end

function RankingView:initTypeTree()
    self.lv1Node = cc.CSLoader:createNode(Res.Lv1Node)
    self.lv2Node = cc.CSLoader:createNode(Res.Lv2Node)
    self.lv3Node = cc.CSLoader:createNode(Res.Lv3Node)
    self.playerNode = cc.CSLoader:createNode(Res.PlayerNode)
    self.playerNode1 = cc.CSLoader:createNode(Res.PlayerNode1)
    self.teamNode = cc.CSLoader:createNode(Res.TeamNode)
    self.memberNode = cc.CSLoader:createNode(Res.MemberNode)
    self.memberGroupNode = cc.CSLoader:createNode(Res.MemberGroupNode)
    
    self.lv1Node:retain()
    self.lv2Node:retain()
    self.lv3Node:retain()
    self.playerNode:retain()
    self.playerNode1:retain()
    self.teamNode:retain()
    self.memberNode:retain()
    self.memberGroupNode:retain()

    self.lv1Node:setAnchorPoint(cc.p(0, 1))

    -- self.typeTree = self.mUINode:findChild("Panel/ListView")
    -- self.typeTree:setGravity(ccui.ListViewGravity.left)
    -- self.typeTree:setItemsMargin(0)

    -- ListView 有bug，使用ScrollView
    local listView = self.mUINode:findChild("Panel/ListView")
    listView:setVisible(false)
    local scrollView = ccui.ScrollView:create()
    self.typeTree = scrollView
    scrollView:setContentSize(listView:getContentSize())
    scrollView:setDirection(ccui.ScrollViewDir.vertical)
    scrollView:setBounceEnabled(true)
    scrollView:setAnchorPoint(cc.p(listView:getAnchorPoint()))
    scrollView:setPosition(listView:getPosition())
    listView:getParent():addChild(scrollView)

    self.selColor = cc.c3b(255,225,132)
    self.idlColor = cc.c3b(172,165,154)
    
    local lastBtn = {}
    local lastLv3Btn = nil
    local function checkLv3Btn(aBtn)
        if lastLv3Btn then
            lastLv3Btn.btnSelect:setTouchEnabled(true)
            lastLv3Btn.btnSelect:setBright(true)  
            lastLv3Btn.lblName:setTextColor(cc.c3b(227,184,109))       
        end

        lastLv3Btn = aBtn 

        if lastLv3Btn then
            lastLv3Btn.btnSelect:setTouchEnabled(false)
            lastLv3Btn.btnSelect:setBright(false)
            lastLv3Btn.lblName:setTextColor(self.selColor)
        end
    end

    local function checkLastBtn(aBtn, aLastIdx)
        if aLastIdx == 1 then
            if lastBtn[2] then
                lastBtn[2].content.btnSelect:setTouchEnabled(true)
                lastBtn[2].content.btnSelect:setBright(true)
                if lastBtn[2].content.selected then
                    lastBtn[2].selectItem()
                end
                lastBtn[2].content.lblName:setTextColor(self.idlColor)                
            end
            lastBtn[2] = nil
        end
        if lastBtn[aLastIdx] and lastBtn[aLastIdx] ~= aBtn then
            lastBtn[aLastIdx].content.btnSelect:setTouchEnabled(true)
            lastBtn[aLastIdx].content.btnSelect:setBright(true)
            if lastBtn[aLastIdx].content.selected then
                lastBtn[aLastIdx].selectItem()
            end    
            lastBtn[aLastIdx].content.lblName:setTextColor(self.idlColor)        
        end 
        lastBtn[aLastIdx] = aBtn 

        lastBtn[aLastIdx].content.btnSelect:setTouchEnabled(false)
        lastBtn[aLastIdx].content.btnSelect:setBright(false)
        lastBtn[aLastIdx].content.lblName:setTextColor(self.selColor)
    end 

    local function ExtendList(i, cn, cnn)
        i.selected = false
        local l = ccui.Layout:create()
        l:setLayoutType(ccui.LayoutType.VERTICAL)
        l:setContentSize(i:findChild("Panel"):getContentSize())
        i:setContentSize(l:getContentSize())
        -- l:setBackGroundColorType(1)
        -- l:setBackGroundColor(cc.c3b(78, 78, 78))
        l:addChild(i)
        l.content = i
        l.getChildren = function()
            if l._children then
               return l._children
            end

            l._children = {}
            l._childrenHeight = 0
            local ocs = i._data.children
            local cs = {}
            for i, v in ipairs(ocs) do
                if checknumber(v.ID) == 110 then
                    local sp = RankingManager:getSpRanking()
                    if #sp > 0 then
                        table.insert(cs, v)
                    end
                else
                    table.insert(cs, v)
                end
            end
            if checknumber(i._data.ID) == 110 then
                cs = RankingManager:getSpRanking()
            end
            if #cs == 1 and cnn then
                cs = cs[1].children or {}
                cn = cnn
            end
            for k, v in ipairs(cs) do
                local sub = cn()
                sub.setData(v)
                sub.parentNode = l

                l:addChild(sub)
                l._childrenHeight = l._childrenHeight + sub:getContentSize().height
                l._children[#l._children + 1] = sub
            end

            return l._children
        end

        l.resetSize = function()
            l._childrenHeight = 0
            for k, v in ipairs(l._children) do
                if v:isVisible() then
                    l._childrenHeight = l._childrenHeight + v:getContentSize().height
                end
            end
            
            l:setContentSize(cc.size(i:getContentSize().width, i:getContentSize().height + l._childrenHeight))

            l.cresetSize()
        end

        l.cresetSize = function()
            if l.parentNode and l.parentNode.resetSize then
                l.parentNode:resetSize()
            end
        end

        l.showChildren = function(b)
            local cs = l.getChildren()
            l._childrenHeight = 0
            for k, v in pairs(cs) do
                v:setVisible(b)
                if v:isVisible() then
                    l._childrenHeight = l._childrenHeight + v:getContentSize().height
                end
            end
        end

        l.colapse = function()
            l:setContentSize(i:getContentSize())
            l.showChildren(false)

            l.cresetSize()
        end 

        l.extend = function(aAchCfg)
            l.showChildren(true)
            l:setContentSize(cc.size(i:getContentSize().width, i:getContentSize().height + l._childrenHeight))

            l.cresetSize()
        end

        l.selectItem = function()
            i.selected = not i.selected

            if i.selected then
                i.lblName:setTextColor(self.selColor)
                if i._data.children and #i._data.children == 1 and checknumber(i._data.children[1].titleshow) == 0 then
                else
                    l.extend()
                end
            else 
                i.lblName:setTextColor(self.idlColor)
                l.colapse()
            end 

            if i.onStatusChange then
                i.onStatusChange()
            end
        end
        return l
    end
    
    local function GetLv3Node()
        local i = self.lv3Node:clone()
        i:setContentSize(i:findChild("Panel"):getContentSize())
        
        -- i.imgUp = i:findChild("Panel/img_2"):show()
        -- i.imgDown = i:findChild("Panel/img_1"):hide()
        i.lblName = i:findChild("Panel/name")
        i.lblName:getVirtualRenderer():setLineSpacing(-6)
        i.btnSelect = i:findChild("Panel/selected_btn")
        i.btnSelect:setPressedActionEnabled(false)
        i.lblName:setTextColor(cc.c3b(227,184,109))   
        i.gift = i:findChild("Panel/icon_gifts")
        i.gift:hide()

        i.select = function()
            checkLv3Btn(i)
            self:requestRank(checknumber(i._data.ID))
        end

        i.btnSelect:addClickEventListener(function()
            i.select()
        end)

        i.setData = function(aD)            
            self.rankMap[checknumber(aD.ID)] = {c = i, p = checknumber(aD.belong)}
            i._data = aD
            if RankingManager:hasRankingReward(checknumber(aD.ID)) then
                i.gift:show()
            end
            i.lblName:setString(L(aD.title))
        end

        return i
    end
    
    local function GetLv2Node()
        local i = self.lv2Node:clone()
        
        i.imgUp = i:findChild("Panel/img_2"):show()
        i.imgDown = i:findChild("Panel/img_1"):hide()
        i.lblName = i:findChild("Panel/name")
        i.btnSelect = i:findChild("Panel/selected_btn")
        i.btnSelect:setPressedActionEnabled(false)
        i.lblName:setTextColor(self.idlColor)

        local l = ExtendList(i, GetLv3Node)

        l.select = function()
            l.selectItem()
            checkLastBtn(l, 2)
        end

        i:findChild("Panel"):addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                l.select()
            end
        end)

        i.btnSelect:addClickEventListener(function()
                l.select()
                local c = i._data.children[1]
                if c then
                    self:open(c.ID)
                end
        end)

        l.setData = function(aD)
            local _fchildren = {}
            for k, v in ipairs(aD.children) do
                local c = RankingManager.hcfg[checknumber(v.ID)]
                if c and checknumber(c.condition1Show) > 0 then
                    if table.indexof(self.copyList, checknumber(c.condition1Show)) then
                        table.insert(_fchildren, v)
                    end
                else
                    table.insert(_fchildren, v)
                end
            end
            aD.children = _fchildren
            self.typeMap[checknumber(aD.ID)] = {c = l, p = checknumber(aD.belong)}
            i._data = aD
            i.lblName:setString(L(aD.title))
        end

        i.onStatusChange = function()
            if i.selected then
                i.imgUp:hide()
                i.imgDown:show()
            else
                i.imgUp:show()
                i.imgDown:hide()
            end

            -- if not (i._data.children and #i._data.children > 1) then
            --     i.imgUp:hide()
            --     i.imgDown:hide()
            -- end
        end

        return l
    end

    local function GetLv1Node()
        local i = self.lv1Node:clone()
        
        i.imgUp = i:findChild("Panel/img_2"):show()
        i.imgDown = i:findChild("Panel/img_1"):hide()
        i.lblName = i:findChild("Panel/name")
        i.btnSelect = i:findChild("Panel/selected_btn")
        i.btnSelect:setPressedActionEnabled(false)
        i.lblName:setTextColor(self.idlColor)
        i:findChild("Panel"):setBackGroundColorType(ccui.LayoutBackGroundColorType.none)

        local l = ExtendList(i, GetLv2Node, GetLv3Node)

        l.select = function()
            l.selectItem()
            checkLastBtn(l, 1)
        end

        l.selectFirstRank = function()
            local c = i._data.children[1]
            if c then
                if c.children[1] then
                    self:open(c.children[1].ID)
                end
            end
        end

        i:findChild("Panel"):addTouchEventListener(function(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                l.select()

                if i.selected then
                    l.selectFirstRank()
                end
            end
        end)

        i.btnSelect:addClickEventListener(function()
            l.select()
            l.selectFirstRank()
        end)

        l.setData = function(aD)
            i._data = aD
            self.typeMap[checknumber(aD.ID)] = {c = l, p = checknumber(aD.belong)}
            i.lblName:setString(L(aD.title))
            i.onStatusChange()
        end

        i.onStatusChange = function()
            if i.selected then
                i.imgUp:hide()
                i.imgDown:show()
            else
                i.imgUp:show()
                i.imgDown:hide()
            end

            -- if not (i._data.children and #i._data.children > 1) then
            --     i.imgUp:hide()
            --     i.imgDown:hide()
            -- end
        end

        return l
    end

    self.resetSize = function()
        -- self.typeTree:requestRefreshView()
        -- self.typeTree:forceDoLayout()
        self:resetTypeTreeSize()
    end

    for k, v in ipairs(RankingManager.rt.children) do
        local i = GetLv1Node()
        i.setData(v)
        i.parentNode = self
        self.typeTree:addChild(i)
    end

    self:resetTypeTreeSize()
end

function RankingView:resetTypeTreeSize()
    local innerSize = self.typeTree:getContentSize()
    local children = self.typeTree:getChildren()

    local innerHeight = 0
    local _, height
    for i,child in ipairs(children) do
        _, height = child:getContentSize2()
        innerHeight = innerHeight + height
    end

    if innerHeight > innerSize.height then
        innerSize.height = innerHeight
    end

    self.typeTree:setInnerContainerSize(innerSize)

    local posY = innerSize.height
    for i,child in ipairs(children) do
        _, height = child:getContentSize2()
        posY = posY - height
        child:setPositionY(posY)
    end
end

function RankingView:gotoSelf()
    if not self.selfNode then
        return
    end

    if self.selfNode.extend then
        self.selfNode.extend()
    end

    self:gotoItem(self.selfNode)    
end

function RankingView:gotoItem(i)
    local off  = self.rankList:getInnerContainerSize().height - self.rankList:getContentSize().height
    if off > 0 then
        local off2 = math.max(0, off - (self.rankList:getInnerContainerSize().height - math.abs(i:getPositionY() + i:getContentSize().height)))
        self.rankList:jumpToPercentVertical(math.max(0, math.min(100, 100 * (1-off2/off))))
    end

    self.onScrollEvt()
end

function RankingView:setIndex(aCtrl, aIndex)
    local r = {}
    for i = 1, 3 do
        r[i] = aCtrl._ui["Panel/Panel_"..tostring(i)]
        r[i]:hide()
    end
    r[4] = aCtrl._ui["Panel/num"]
    if r[4] then
        r[4]:hide()
        if aIndex >= 4 then
            r[4]:show()
            r[4]:setString(tostring(aIndex))
        end
    end

    if aIndex < 4 and aIndex > 0 then
        r[aIndex]:show()
    end  
end

function RankingView:setPlayer(aData, aCtrl, aIndex, aRt, aRid)
    aCtrl._ui.name:setString(L(aData.userBaseInfo.name))
    if rawget(aData, "server") then
        aCtrl._ui.server:setVisible(true)
        aCtrl._ui.server:setString(app.channelAPI:getServerNameByIndex(aData.server))
        aCtrl._ui.name:setPositionY(59)
    else
        aCtrl._ui.server:setVisible(false)
        aCtrl._ui.name:setPositionY(47)
    end
    local bg = aCtrl._ui.bg_my
    bg:hide()

    local btnDetail = aCtrl._ui.Button_1
    btnDetail:show()
    if aData.userBaseInfo.uid < 0 or RankingManager:isEliteMatchRank(aRid) then
        -- 机器人不显示交互按钮, 跨服角色也不显示交互按钮
        btnDetail:hide()
    end

    if UD.uid == aData.userBaseInfo.uid then
        self.selfNode = aCtrl
        self.myPerRank = aIndex
        bg:show()
        btnDetail:hide()
        if aRid == 2 and not UD.localStorage:isRankAdReport() then
            EM:notify("onInTheScoreRanking")
            UD.localStorage:setRankAdReportTime(app.session:getServerTime())
			UD:updateLocalStorage(UD.localStorage)
        end
    end

    btnDetail:addClickEventListener(function()
        UIHandler:showHeadMenu({online=true, attr=UserBaseInfo.new(aData.userBaseInfo), 
        pos=btnDetail:getParent():convertToWorldSpace(cc.p(btnDetail:getPositionX(), btnDetail:getPositionY()))})
    end)

    self:setIndex(aCtrl, aIndex)
    --display.pushToast( L("lua_code_text_458") )
    -- set head
    local h = aCtrl._ui.head
    local lblLv = aCtrl._ui["Panel/head/Panel/Panel_lv/num"]
    local icoClass = aCtrl._ui["Panel/head/Panel/class_icon"]
    local icoHead = aCtrl._ui["Panel/head/Panel/icon"]
    icoHead:show()

    local pl = aCtrl._ui["Panel/head/Panel/Panel_lv"]
    
    if aRid == 1 or table.indexof(self.columns, 2) then
        pl:hide()
    end

    lblLv:setString(tostring(aData.userBaseInfo.lv))
    local classIconPath = GD:getClassIcon( aData.userBaseInfo.classID, 2 )
    icoClass:loadTexture( classIconPath )
    icoHead:hide()
    table.insert(self.heads, {d = aData.userBaseInfo, c = icoHead})
    -- AvatarFactotry.getOrCreateHeroIconPath(aData.userBaseInfo,function(iconPath)
    --     if iconPath then
    --         icoHead:loadTexture(iconPath)
    --     end
    -- end)

    local c1 = aCtrl._ui.job
    local c2 = aCtrl._ui.combat
    local valCol = aCtrl._ui.time

    c1:show()
    -- c2:show()
    valCol:show()

    local function getValStr(aT)
        local ret = ""
        -- aData.userBaseInfo.guildName
        -- os.date("%H:%M:%S", aData.stamp)
        if aT == 1 then
            -- ret = "职业"
            ret = GD:getClassName(aData.userBaseInfo.classID)
        elseif aT == 2 then
            -- ret = "等级"
            ret = tostring(aData.userBaseInfo.lv)
        elseif aT == 3 then
            -- ret = "战力"
            ret = tostring3(aData.userBaseInfo.combatPower)
        end

        return ret
    end
    -- c1:setString(tostring(aData.value))
    c1:setString(getValStr(self.columns[2]))

    
    if #self.columns == 3 and c2 then
        c2:setString(getValStr(self.columns[3]))
    end 
    if self.columnsFmt == 0 then
        valCol:setString(tostring(aData.value))
    elseif self.columnsFmt == 1 then
        valCol:setString(tostring3(aData.value))
    elseif self.columnsFmt == 2 then
        valCol:setString(string.format("%.2f", math.max(aData.value, 36)/3600))
    elseif self.columnsFmt == 3 then
        -- local m = aData.value/60
        -- local s = math.fmod(aData.value, 60)
        valCol:setString( RankingManager:hmstr(aData.value) )
    else
        valCol:setString(tostring(aData.value))
    end

    local qqBtn1 = aCtrl._ui.btn_qq_1
    local qqBtn2 = aCtrl._ui.btn_qq_2
    local wxBtn = aCtrl._ui.btn_wx

    local wakeUp = rawget(aData, "wakeUpFrom")
    if not wakeUp then
        wakeUp = Enums.WAKE_UP.NONE
    end
    qqBtn1:setVisible(UD.msdkData:isWakeUpFromQQGame(wakeUp))
    wxBtn:setVisible(UD.msdkData:isWakeUpFromWXGame(wakeUp))
    qqBtn2:setVisible(false)

    qqBtn1:addClickEventListener(function()
        UD.msdkData:qqGameCenterClickTip()
    end)
    qqBtn2:addClickEventListener(function()
        UD.msdkData:qqVipClickTip()
    end)
    wxBtn:addClickEventListener(function()
        UD.msdkData:wxGameCenterClickTip()
    end)
end

function RankingView:refreshRewardsViewBtn(aId)
    self.currentRank = aId
    self.btnGift:setVisible(RankingManager:hasRankingReward(aId))
end

function RankingView:requestRank(aId)
    self:refreshColumnHead(aId)
    self:refreshPage(0)
    self:setMyScore(L("lua_code_text_153"))
    self:refreshRewardsViewBtn(aId)
    if RankingManager:isTeamRank(aId) then
        RankingManager:requestTeamRank(aId)
    elseif RankingManager:isEliteMatchRank(aId) then
        RankingManager:requestWorldRank(aId)
    else
        RankingManager:requestRank(aId)
    end    
end

function RankingView:refreshColumnHead(aId)
    self.columns = {99}
    self.columnsFmt = 0
    local c = RankingManager.hcfg[checknumber(aId)]
    self.columnsFmt = checknumber(c.count)
    local rtype = 0
    if c then
        rtype = checknumber(c.Subtitle1)
        if rtype > 0 then
            table.insert(self.columns, rtype)
        end
        rtype = checknumber(c.Subtitle2)
        if rtype > 0 then
            table.insert(self.columns, rtype)
        end
        
        local curCol = self.columnPanel
        self.columnPanel:show()
        self.columnPanel_1:hide()
        if #self.columns == 2 then
            self.columnPanel:hide()
            self.columnPanel_1:show()

            curCol = self.columnPanel_1
        end

        local c1 = curCol:findChild("job")
        local c2 = curCol:findChild("combat")
        local hval = curCol:findChild("time")
        local tipsBtn = curCol:findChild("btn_tips")

        local function getCName(aT)
            local ret = ""
            if aT == 1 then
                ret = L("lua_code_text_390")
            elseif aT == 2 then
                ret = L("lua_code_text_379")
            elseif aT == 3 then
                ret = L("lua_code_text_402")
            elseif aT == 4 then
                ret = L("lua_code_text_162")
            elseif aT == 5 then
                ret = L("lua_code_text_408")
            end

            return ret
        end

        c1:setString(getCName(self.columns[2]))

        if self.columns[3] and hval and c2 then
            c2:setString(getCName(self.columns[3]))
        end
        hval:setString(L(c.list))      
        if tipsBtn and RankingManager:isEliteMatchRank(checknumber(aId)) then    
            tipsBtn:setVisible(true)
            tipsBtn:setPositionX(self._tipsPosX+10)
        elseif tipsBtn then
            tipsBtn:setVisible(false)
        end
    end
end

function RankingView:setMyScore(str)
    if self.lblMyScore then
        self.lblMyScore:setString(str)
        local strs = self.lblMyScore:getContentSize()
        local bgs = self.lblMyScoreBg:getContentSize()

        if self.btnGift:isVisible() then
            local gsz = self.btnGift:getContentSize()
            local px, py = self.lblMyScore:getPosition()
            self.btnGift:setPosition(cc.p(px + strs.width + 20, py))
            self.lblMyScoreBg:setContentSize(cc.size(strs.width+100+gsz.width, bgs.height))
        else
            self.lblMyScoreBg:setContentSize(cc.size(strs.width+100, bgs.height))
        end
    end
end

function RankingView:beginRefreshView(aId)
    self.asyncRefreshViewId = aId
    self.asyncRefreshCount = 0
    self.asyncRefreshCountMax = #(RankingManager.serverrank[aId].infos)
    self.rankList:jumpToTop()
    self:poolItems()
    self.selfNode = nil
    self.myPerRank = -1
    self.pageStarts = {}
    self.heads = {}
end

function RankingView:refreshView(aId, step)
    local idxStart = self.asyncRefreshCount + 1
    local idxEnd = self.asyncRefreshCount + step
    local playerNodeSize = self.playerNode:findChild("Panel"):getContentSize()
    local ds = RankingManager.serverrank[aId].infos
    local n
    local v
    for idx = idxStart, idxEnd do
        v = ds[idx]
        if v == nil then
            break
        end
        if #self.columns == 2 then
            self.lastNodeType = 1
            n = self.NodePool:getByKey("ranking_view_1") or self.playerNode1:clone()
        else
            self.lastNodeType = 2
            n = self.NodePool:getByKey("ranking_view") or self.playerNode:clone()
        end
        n:setContentSize(playerNodeSize)

        if n._ui == nil then
            n._ui = display.uiDelegate(n)
        end
        
        self:setPlayer(v, n, idx, 1, aId)
        
        if math.fmod(idx, 20) == 1 then
            table.insert(self.pageStarts, n)
        end
        self.rankList:pushBackCustomItem(n)
    end
end

function RankingView:getCosplayConfig(bnpcid)
    if checknumber(bnpcid) == 0 then
        bnpcid = 20101
        release_print("================> RankingView:getCosplayConfig() bnpc id is 0!")
    end
    local ccfg = GD:queryCosplayConf(bnpcid)
    local specIcon = GD:getSpec_typeConfig(ccfg.specID).featureIcon_1
    
    return {
        name = L(ccfg.dutyShow),
        path = Res.classIconPath..specIcon..".png",
        shead = Res.cosplayIconPath:format(ccfg.head),
        ehead = Res.cosplayIconPath:format(ccfg.head1),
    }
end

function RankingView:setTeam(aData, aCtrl, aIndex)
    self:setIndex(aCtrl, aIndex)

    local chars = aData.infos
    local teamleader = chars[1].baseInfo
    for i, v in ipairs(chars) do
        if v.baseInfo.uid == aData.leaderId then
            teamleader = v.baseInfo 
        end
    end

    aCtrl._ui["Panel/name"]:setString(L(teamleader.name)..L("lua_code_text_476"))
    local totalCombat = 0
    local ismyteam = false

    if #chars > 5 then
        for i = 1, 5 do
            local c = aCtrl._ui["Panel/class_"..tostring(i)]
            c:hide()
        end
        aCtrl._ui["Panel/Panel_legion_class"]:setVisible(true)
        for i = 1, 10 do
            local c = aCtrl._ui["Panel/Panel_legion_class/class_"..tostring(i)]
            if chars[i] then
                c:show()

                if chars[i].baseInfo.uid == UD.uid then
                    ismyteam = true
                end

                local cfg = self:getCosplayConfig(chars[i].bnpcId)
                c:loadTexture(cfg.path)
                totalCombat = totalCombat + chars[i].baseInfo.combatPower
            else
                c:hide()
            end
        end
    else
        for i = 1, 5 do
            local c = aCtrl._ui["Panel/class_"..tostring(i)]
            if chars[i] then
                c:show()

                if chars[i].baseInfo.uid == UD.uid then
                    ismyteam = true
                end

                local cfg = self:getCosplayConfig(chars[i].bnpcId)
                c:loadTexture(cfg.path)
                totalCombat = totalCombat + chars[i].baseInfo.combatPower
            else
                c:hide()
            end
        end
    end

    if ismyteam and self.selfNode == nil then
        self.selfNode = aCtrl
        self.myPerRank = aIndex
    end

    aCtrl._ui.combat:setString(tostring(os.date("%Y-%m-%d", aData.stamp)))    
    aCtrl._ui.time:setString(RankingManager:hmstr(aData.sec))

    local function createTeamPanel()
        local ret
        if #chars > 5 then
            ret = self.memberGroupNode:clone()
        else
            ret = self.memberNode:clone()
        end
        ret:setContentSize(ret:findChild("Panel"):getContentSize())

        return ret
    end

    local function refreshTeamData()
        if aCtrl.memberPanel then
            local p = aCtrl.memberPanel:findChild("Panel")
            -- p:findChild("Panel_legion"):hide()

            --这里比较麻烦 我们分为10人和5人的
            if #chars > 5 then
                for i = 1, 10 do
                    local player = p:findChild("player"..tostring(i))
                    if chars[i] then
                        local bnpcconfig = self:getCosplayConfig(chars[i].bnpcId)
                        local h = HeadRender.create(player:findChild("Panel/Panel_withData/head"), 3)
                        h:setData( cloneWithoutMeta(chars[i].baseInfo) )
                        h:findChild("Panel/class_icon"):loadTexture(bnpcconfig.path)
                        if ismyteam then
                            h:findChild("Panel/icon"):loadTexture(bnpcconfig.shead)
                        else
                            h:findChild("Panel/icon"):loadTexture(bnpcconfig.ehead)
                        end

                        h:onClick(function()
                            if chars[i].baseInfo.uid == UD.uid then return end
                            UIHandler:showHeadMenu({online=true, attr=UserBaseInfo.new(chars[i].baseInfo),
                                pos=h:getParent():convertToWorldSpace(cc.p(h:getPositionX(), h:getPositionY()))})
                        end)

                        player:findChild("Panel/Panel_withData/name"):setString(L(chars[i].baseInfo.name))
                        if chars[i].baseInfo.uid ~= aData.leaderId then
                            player:findChild("Panel/Panel_withData/name"):setTextColor(cc.c3b(108,158,239))
                        else
                            player:findChild("Panel/Panel_withData/name"):setTextColor(cc.c3b(255,255,255))
                        end
                        player:findChild("Panel/Panel_withData/lv_num"):setVisible(false)
                        player:findChild("Panel/Panel_withData/combat_icon"):setVisible(false)
                        player:findChild("Panel/Panel_withData/text_zhiye"):setVisible(true)

                        player:findChild("Panel/Panel_withData/text_zhiye"):setString(bnpcconfig.name)
                        -- player:findChild("Panel/Panel_withData/combat_num"):setString(L(tostring(chars[i].combatPower)))
                        -- print("----", chars[i].uid , aData.leaderId)
                        player:findChild("Panel/Panel_withData/icon_leader"):setVisible(chars[i].baseInfo.uid == aData.leaderId)
                        player:findChild("Panel/Panel_withData/Image_Forbidden"):hide()
                        player:findChild("Panel/Panel_withData/partner"):setVisible(false)

                    else
                        player:findChild("Panel/Panel_withData"):hide()
                    end
                end
            else
                for i = 1, 5 do
                    local player = p:findChild("Panel_team/player0"..tostring(i))
                    if chars[i] then
                        player:findChild("Panel/Panel_withData"):show()
                        -- player:findChild("Panel/stop"):hide()
                        local bnpcconfig = self:getCosplayConfig(chars[i].bnpcId)
                        local h = HeadRender.create(player:findChild("Panel/Panel_withData/head"), 3)
                        h:setData( cloneWithoutMeta(chars[i].baseInfo) )
                        h:findChild("Panel/class_icon"):loadTexture(bnpcconfig.path)
                        if ismyteam then
                            h:findChild("Panel/icon"):loadTexture(bnpcconfig.shead)
                        else
                            h:findChild("Panel/icon"):loadTexture(bnpcconfig.ehead)
                        end

                        h:onClick(function()
                            if chars[i].baseInfo.uid == UD.uid then return end
                            UIHandler:showHeadMenu({online=true, attr=UserBaseInfo.new(chars[i].baseInfo),
                                pos=h:getParent():convertToWorldSpace(cc.p(h:getPositionX(), h:getPositionY()))})
                        end)

                        player:findChild("Panel/Panel_withData/name"):setString(L(chars[i].baseInfo.name))
                        if chars[i].baseInfo.uid ~= aData.leaderId then
                            player:findChild("Panel/Panel_withData/name"):setTextColor(cc.c3b(108,158,239))
                        else
                            player:findChild("Panel/Panel_withData/name"):setTextColor(cc.c3b(255,255,255))
                        end
                        player:findChild("Panel/Panel_withData/lv_tlt"):setString(string.format(L("lua_code_text_291"), chars[i].baseInfo.lv))

                        player:findChild("Panel/Panel_withData/class"):setString(bnpcconfig.name)
                        -- player:findChild("Panel/Panel_withData/combat_num"):setString(L(tostring(chars[i].combatPower)))
                        -- print("----", chars[i].uid , aData.leaderId)
                        player:findChild("Panel/Panel_withData/icon_leader"):setVisible(chars[i].baseInfo.uid == aData.leaderId)
                        player:findChild("Panel/Panel_withData/Image_Forbidden"):hide()
                        player:findChild("Panel/Panel_withData/partner"):setVisible(false)
                    else
                        player:findChild("Panel/Panel_withData"):hide()
                        -- player:findChild("Panel/stop"):show()
                    end
                end
            end
        end
    end

    refreshTeamData()

    local btn = aCtrl._ui.Button_1    
    local btnName = aCtrl._ui["Panel/Button_1/name"]
    local teamItem = aCtrl._ui.Panel
    btn:addClickEventListener(function(sender)
        aCtrl.extend()
        self:gotoItem(aCtrl)
    end)

    aCtrl.extend = function()
        btn:setTouchEnabled(false)
        btn:setBright(false)
        btnName:setString(L("lua_code_text_120"))

        if not aCtrl.memberPanel then
            aCtrl.memberPanel = createTeamPanel()
            refreshTeamData()
            aCtrl:addChild(aCtrl.memberPanel, -1)
        end

        local cs = aCtrl.memberPanel:getContentSize()
        local itemsize = teamItem:getContentSize()
        aCtrl:setContentSize(cc.size(itemsize.width, itemsize.height + cs.height))
        teamItem:setPosition(cc.p(0, cs.height))
        aCtrl.memberPanel:show()

        if self.lastTeamPanel ~= nil and self.lastTeamPanel ~= aCtrl then
            self.lastTeamPanel.colapse()
        end

        self.lastTeamPanel = aCtrl

        self.rankList:requestRefreshView()
        self.rankList:forceDoLayout()
    end

    aCtrl.colapse = function()
        btn:setTouchEnabled(true)
        btn:setBright(true)
        btnName:setString(L("lua_code_text_126"))
        
        aCtrl:setContentSize(teamItem:getContentSize())
        teamItem:setPosition(cc.p(0, 0))
        if aCtrl.memberPanel then
            aCtrl.memberPanel:hide()
        end
    end

    local bg1 = aCtrl._ui.bg1
    bg1:setTouchEnabled(true)
    bg1:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            aCtrl.colapse()

            self.rankList:requestRefreshView()
            self.rankList:forceDoLayout()
        end
    end)
end

function RankingView:poolItems()
    local items = self.rankList:getItems()
    for k, v in ipairs(items) do
        if not cc.isDead(v) then
            if self.lastNodeType == 1 then
                self.NodePool:put(v, "ranking_view_1")
            elseif self.lastNodeType == 2 then
                self.NodePool:put(v, "ranking_view")
            elseif self.lastNodeType == 3 then
                if v.colapse then
                    v.colapse()
                end
                self.NodePool:put(v, "ranking_view_team")
            end
        end
    end
    self.rankList:removeAllChildren()
end
function RankingView:refreshTeamView(aId, step)
    local idxStart = self.asyncRefreshCount + 1
    local idxEnd = self.asyncRefreshCount + step
    local teamNodeSize = self.teamNode:findChild("Panel"):getContentSize()
    local ds = RankingManager.serverrank[aId].infos
    local n
    local v
    for idx = idxStart, idxEnd do
        v = ds[idx]
        if v == nil then
            break
        end

        local n = self.NodePool:getByKey("ranking_view_team") or self.teamNode:clone()
        self.lastNodeType = 3
        n:setContentSize(teamNodeSize)
        
        if n._ui == nil then
            n._ui = display.uiDelegate(n)
        end

        self:setTeam(v, n, idx)

        local bg = n._ui.bg_my
        bg:hide()
        if checknumber(RankingManager.serverrank[aId].myRank) == idx then
            bg:show()
        end
        
        if math.fmod(idx, 20) == 1 then
            table.insert(self.pageStarts, n)
        end
        self.rankList:pushBackCustomItem(n)
    end
end

function RankingView:_showTips(sender)
    local contents = {}
    local part = {}
    table.insert(part, {text = L("ranktips2"), color = cc.c3b(255, 225, 132)})
    table.insert(part, {text = L("ranktips3"), color = cc.c3b(183, 183, 183)})
    table.insert(part, {text = L("ranktips4"), color = cc.c3b(255, 225, 132)})
    table.insert(contents, part)

    local touchPos = sender:getTouchEndPosition()
    local p = sender:convertToWorldSpace(cc.p(0,0))
    local height = sender:getContentSize().height

    local param = {tipsType = Enums.TipsType.contents,contents = contents, closeCallBack = function() app:dispatchCustomEvent("EVENT_CLOSE_FLOAT") end}
    UIHandler:setLastTouchPosition(p.x , p.y)
    app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params=param})
end

return RankingView